;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Enterprise.Partner", [])
        .controller("PartnerCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allChecked: false
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.boundObj = {};
            $scope.submitted = false;
            $scope.condition = {};
            
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };

            $scope.dataList = [];
            
            $scope.detailInfo = {
                dealerType: 5,
                dealerLevel: 1,
                marketingCenterName: '徐州特机工程机械有限公司',
                marketingCenterCode: 'xgtejiyingxiao1115',
            };

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.tbConf = {
                fixedWidth: 200,
                scrollWidth: 1500,
                tableCol: [
                    {
                        name: "业务伙伴编号",
                        width: 150,
                        dataField: "dealerCode",
                        isShow: true,
                        isFixed: false,
                    },
                    /* {
                        name: "ERP账号",
                        width: 150,
                        dataField: "yhbh",
                        isShow: true,
                        isFixed: false,
                    }, */
                    {
                        name: "登录账号",
                        width: 150,
                        dataField: "platOrgId",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "业务伙伴名称",
                        width: 150,
                        dataField: "companyName",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "业务伙伴类别",
                        width: 150,
                        dataField: "dealerTypeShow",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "业务伙伴代码",
                        width: 150,
                        dataField: "dealerOrgId",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "业务伙伴简称",
                        width: 150,
                        dataField: "shortName",
                        isShow: true,
                        isFixed: false,
                    },
                    /* {
                        name: "所属营销中心(道路)",
                        width: 150,
                        dataField: "marketingCenterName",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "所属营销中心(非道路)",
                        width: 150,
                        dataField: "marketingCenterName2",
                        isShow: true,
                        isFixed: false,
                    }, */
                    {
                        name: "地址",
                        width: 200,
                        dataField: "address",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "联系人",
                        width: 100,
                        dataField: "contact",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "联系方式",
                        width: 100,
                        dataField: "contactTel",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "创建日期",
                        dataField: "createDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "操作",
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };


            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tbConf.fixedWidth + "px"
                    }
                };
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                if (index == 0) {
                    initData();
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.boundObj = {};
                $scope.detailInfo = {
                    dealerType: 5,
                    dealerLevel: 1,
                    marketingCenterName: '徐州特机工程机械有限公司',
                    marketingCenterCode: 'xgtejiyingxiao1115',
                };
            }

            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/companyDealer/listTejiWeixiu";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                param.filters.dealerTypeList = [5];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.markInfo.allChecked = false;
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.dealerTypeShow = $filter("DealerType")(item.dealerType);
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
            };

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.delData = function (delType, id) {
                var service = "device";
                var reqUrl = "/companyDealer/remove";
                var param = { ids: [] };
                if (delType === "single") {
                    param.ids.push(id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            param.ids.push($scope.dataList[i].id);
                        }
                    }
                    if (param.ids.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.editData = function (item) {
                $scope.detailInfo = JSON.parse(JSON.stringify(item));
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(1);
            };


            /* $scope.selectDealer = function () {
                if (!$scope.detailInfo.dealerType) {
                    ybWidget.ShowMessage("请先选择业务伙伴类别", MESG_TYPE.Error);
                    return
                }
                let options = {}
                if ($scope.detailInfo.dealerType==2) {
                    options = {
                        title: '业务伙伴',
                        service: 'sync',
                        url: '/lswldw/list',
                        otherParams: { isstop: 0 },
                        keyWords: [{label: '业务伙伴名称', field: 'nameLike'}, {label: '业务伙伴编号', field: 'lswldwWldwbh'}],
                        fields: [
                            {
                                name: '业务伙伴名称',
                                dataField: 'lswldwDwmc',
                                width: "40%"
                            },
                            {
                                name: '业务伙伴编号',
                                dataField: 'lswldwWldwbh',
                                width: "30%"
                            },
                            {
                                name: 'ERP账号',
                                dataField: 'erpusecode',
                                width: "30%"
                            }
                        ]
                    }
                }
                if ($scope.detailInfo.dealerType==5) {
                    options = {
                        title: '业务伙伴',
                        service: 'sync',
                        url: '/crmfwz/list',
                        keyWords: [{label: '业务伙伴名称', field: 'nameLike'}, {label: '业务伙伴编号', field: 'fwzh'}],
                        fields: [
                            {
                                name: '业务伙伴名称',
                                dataField: 'fwzmc',
                                width: "40%"
                            },
                            {
                                name: '业务伙伴编号',
                                dataField: 'fwzh',
                                width: "30%"
                            },
                            {
                                name: 'ERP账号',
                                dataField: 'yhbh',
                                width: "30%"
                            }
                        ]
                    }
                }
                ybWidget.DataSelector(options).then(function (data) {
                    if ($scope.detailInfo.dealerType==2) {
                        $scope.detailInfo.dealerCode = data.lswldwWldwbh
                        $scope.detailInfo.companyName = data.lswldwDwmc

                        $scope.detailInfo.yhbh = data.erpusecode
                        $scope.detailInfo.yhmc = data.erpusename
                    }
                    if ($scope.detailInfo.dealerType==5) {
                        $scope.detailInfo.dealerCode = data.fwzh
                        $scope.detailInfo.companyName = data.fwzmc

                        $scope.detailInfo.shortName = data.fwzjc
                        $scope.detailInfo.contact = data.zz
                        $scope.detailInfo.contactTel = data.zzdh

                        $scope.detailInfo.address = data.dz
                        $scope.detailInfo.zb = data.zb
                        $scope.detailInfo.marketingCenterName = data.ssxsfwzxdlmc
                        $scope.detailInfo.marketingCenterCode = data.ssxsfwzxdlbh
                        $scope.detailInfo.marketingCenterName2 = data.ssxsfwzxfdlmc
                        $scope.detailInfo.marketingCenterCode2 = data.ssxsfwzxfdlbh

                        $scope.detailInfo.yhbh = data.yhbh
                        $scope.detailInfo.yhmc = data.yhmc
                    }
                })
            };

            $scope.clearDealer = function(clearAll) {
                $scope.detailInfo.dealerCode = ''
                $scope.detailInfo.companyName = ''

                $scope.detailInfo.yhbh = ''
                $scope.detailInfo.yhmc = ''

                if ($scope.detailInfo.dealerType==5 || clearAll) {
                    $scope.detailInfo.shortName = ''
                    $scope.detailInfo.contact = ''
                    $scope.detailInfo.contactTel = ''

                    $scope.detailInfo.address = ''
                    $scope.detailInfo.zb = ''
                    $scope.detailInfo.marketingCenterName = ''
                    $scope.detailInfo.marketingCenterCode = ''
                    $scope.detailInfo.marketingCenterName2 = ''
                    $scope.detailInfo.marketingCenterCode2 = ''
                }
            }; */

            $scope.selectDealer = function () {
                const options = {
                    title: '业务伙伴',
                    service: 'device',
                    url: '/companyDealer/list',
                    otherParams: { isPlatCompany: true },
                    keyWords: [{label: '客户编号', field: 'dealerCode'}, {label: '客户名称', field: 'companyName'}],
                    fields: [
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        },
                        {
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                    ]
                }
                ybWidget.DataSelector(options).then(function (data) {
                    const addressTemp = $scope.detailInfo.address;
                    const provinceTemp = $scope.detailInfo.province;
                    const cityTemp = $scope.detailInfo.city;
                    const zbTemp = $scope.detailInfo.zb;

                    $scope.detailInfo = {
                        ...data,
                        dealerType: 5,
                        dealerLevel: 1,
                        marketingCenterName: '徐州特机工程机械有限公司',
                        marketingCenterCode: 'xgtejiyingxiao1115',
                    };

                    $scope.detailInfo.address = addressTemp;
                    $scope.detailInfo.province = provinceTemp;
                    $scope.detailInfo.city = cityTemp;
                    $scope.detailInfo.zb = zbTemp;
                })
            };

            $scope.clearDealer = function() {
                const addressTemp = $scope.detailInfo.address;
                const provinceTemp = $scope.detailInfo.province;
                const cityTemp = $scope.detailInfo.city;
                const zbTemp = $scope.detailInfo.zb;

                $scope.detailInfo = {
                    dealerType: 5,
                    dealerLevel: 1,
                    marketingCenterName: '徐州特机工程机械有限公司',
                    marketingCenterCode: 'xgtejiyingxiao1115',
                };

                $scope.detailInfo.address = addressTemp;
                $scope.detailInfo.province = provinceTemp;
                $scope.detailInfo.city = cityTemp;
                $scope.detailInfo.zb = zbTemp;
            };

            $scope.handleCompanyTypeChange = function() {
                $scope.clearDealer(true);
            };

            $scope.selectMarketingCenter = function (type) {
                let options = {
                    title: '销售服务中心',
                    service: 'sync',
                    url: '/ynMarketingCenter/list',
                    keyWords: [{label: '销售服务中心名称', field: 'nameLike'}, {label: '销售服务中心代码', field: 'code'}],
                    fields: [
                        {
                            name: '销售服务中心名称',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '销售服务中心代码',
                            dataField: 'code',
                            width: "50%"
                        }
                    ]
                }

                if (type == 'DL') {
                    options.otherParams = { ytdx: '0' }
                } else if (type == 'FDL') {
                    options.otherParams = { ytdx: '1' }
                }
                ybWidget.DataSelector(options).then(function (data) {
                    if (type == 'DL') {
                        $scope.detailInfo.marketingCenterName = data.name
                        $scope.detailInfo.marketingCenterCode = data.code
                    } else if (type == 'FDL') {
                        $scope.detailInfo.marketingCenterName2 = data.name
                        $scope.detailInfo.marketingCenterCode2 = data.code
                    }
                })
            };

            $scope.clearMarketingCenter = function (type) {
                if (type == 'DL') {
                    $scope.detailInfo.marketingCenterName = ''
                    $scope.detailInfo.marketingCenterCode = ''
                } else if (type == 'FDL') {
                    $scope.detailInfo.marketingCenterName2 = ''
                    $scope.detailInfo.marketingCenterCode2 = ''
                }
            };

            // 地图上选择位置
            $scope.selectAddress = function () {
                const abT = $scope.detailInfo.zb || ','
                const options = {
                    "lng": abT.split(',')[0],
                    "lat": abT.split(',')[1],
                    "address": $scope.detailInfo.address
                }
                ybWidget.SelwGaodeMap(options).then(function({ a, b, c }) {
                    $scope.detailInfo.address = a
                    $scope.detailInfo.province = b[0];
                    $scope.detailInfo.city = b[1];
                    $scope.detailInfo.zb = c[0] + ',' + c[1]
                })
            };

            // 删除所选的位置
            $scope.clearAddress = function () {
                $scope.detailInfo.address = ''
                $scope.detailInfo.province = ''
                $scope.detailInfo.city = ''
                $scope.detailInfo.zb = ''
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/companyDealer/updateTejiWeixiu";

                ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.restPwd = function (val) {
                var param = {
                    orgId: val
                };
                ybWidget.ShowMessage("确定将密码重置为xcmg123.吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get('auth', '/auth/resetAdminPasswordByOrgId', param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                    });
                }, function () {});
            };

            $scope.handleInvite = function (id) {
                var service = "device";
                var reqUrl = "/companyDealer/invite";
                ybHttp.Post(service, reqUrl, { id: id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowMessage('邀请码为' + resp.value, MESG_TYPE.Success);
                });
            };


            var btnPermissionCode = {
                partnerAdd: window.ActionCode.partnerAdd,
                partnerEdit: window.ActionCode.partnerEdit,
                partnerDel: window.ActionCode.partnerDel,
                partnerRestPwd: window.ActionCode.partnerRestPwd,
                partnerInvite: window.ActionCode.partnerInvite,
            };

            $scope.btnPermission = {
                partnerAdd: true,
                partnerEdit: true,
                partnerDel: true,
                partnerRestPwd: true,
                partnerInvite: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }


            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
